//
//  WJMeViewController.m
//  BeDeJie
//
//  Created by jerry on 2017/1/25.
//  Copyright © 2017年 jerry. All rights reserved.
//

#import "WJMeViewController.h"
#import "WJSettingViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import "WJSquareItem.h"
#import "WJSquareCell.h"
#import "WJWebViewController.h"
#import "WJPersonalCenterViewController.h"
#import "WJPhotoViewController.h"


static NSString * const ID = @"cell";
static NSInteger const cols = 4;
static CGFloat const margin = 1;
#define itemWH (screenWidth - (cols - 1) * margin) / cols

@interface WJMeViewController () <UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,strong) NSMutableArray *squareItems;
@property (nonatomic,weak) UICollectionView *collectionView;
@end

@implementation WJMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置背景色
    self.view.backgroundColor = WJColor(206, 206, 206);
    
    //设置导航条
    [self setupNavBar];
    
    //设置tableView的底部视图
    [self setupFootView];
    
    //展示方块内容
    [self loadData];
    
    //设置每一个section的头部和底部的高度，使之呈现分隔的效果
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = WJMarin;
    //设置表格四周的间隔(上左下右)
    self.tableView.contentInset = UIEdgeInsetsMake(WJMarin, 0, 0, 0);
    
    //监控tabBar重复点击的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarButtonDidRepeatClick) name:WJTabBarButtonDidRepeatClickNotification object:nil];
}

- (void)dealloc{
    //清除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 监听
// 监听tabBarButton重复点击
- (void)tabBarButtonDidRepeatClick{
    //若控制器没有添加到窗体，则返回
    if (self.view.window == nil) return;
    
    WJFunc;
}

- (void)setupNavBar {
    // 设置
    UIBarButtonItem *settingItem =  [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"icon_navbar_settings_normal"]
                                                         highImage:[UIImage imageNamed:@"icon_navbar_settings_selected"]
                                                            target:self
                                                            action:@selector(setting)];
    // 夜间模型
    UIBarButtonItem *nightItem =  [UIBarButtonItem itemWithImage:[UIImage imageNamed:@"icon_navbar_moon_normal"]
                                                        selImage:[UIImage imageNamed:@"icon_navbar_moon_selected"]
                                                          target:self
                                                          action:@selector(night:)];
    self.navigationItem.rightBarButtonItems = @[settingItem,nightItem];
    
    // 中间的标题
    self.navigationItem.title = @"我的";
    
}

- (void)night:(UIButton *)button{
    button.selected = !button.selected;
}

#pragma mark - 设置就会调用
- (void)setting{
    // 跳转到设置界面
    WJSettingViewController *settingViewController = [[WJSettingViewController alloc] init];
    // 必须要在跳转之前设置
    settingViewController.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:settingViewController animated:YES];
    
}

-(void) loadData {
    //创建会话管理器
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"square";
    params[@"c"] = @"topic";
    
    //发送请求
    [manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseObject) {
        
        //获取方块信息
        NSArray *array = responseObject[@"square_list"];
        
        //转为模型数组
        self.squareItems = [WJSquareItem mj_objectArrayWithKeyValuesArray:array];
        
        //处理数据
        [self resloveData];
        
        NSInteger count = self.squareItems.count;
        //总共有多少行，计算公式：(count - 1) / cols + 1
        NSInteger rows = (count -1) /cols + 1;
        //UICollectionView的高度＝行数 * 元素的高度
        self.collectionView.wj_height = rows * itemWH;
        //UITableView的底部视图　设置为 重新计算好高度的 UICollectionView.
        //UITableView会重新计算tableview的滚动范围
        self.tableView.tableFooterView = self.collectionView;
        
        //刷新表格
        [self.collectionView reloadData];

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        WJLog(@"获取方块内容错误");
    }];
}

//处理数据
- (void) resloveData {
    //判断一行中，有几个空位，空位地方用WJSquareItem空对象代替
    NSInteger count = self.squareItems.count;
    NSInteger exter = count % cols;
    if (exter) {
        //剩余的空位
        exter = cols - exter;
        for (int i=0; i<exter; i++) {
            WJSquareItem *item = [[WJSquareItem alloc] init];
            [self.squareItems addObject:item];
        }
    }
}

//设置tableView的底部视图
- (void)setupFootView {
    //创建布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    //设置cell尺寸
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    
    //设置分隔线尺寸
    layout.minimumLineSpacing = margin;
    layout.minimumInteritemSpacing = margin;
    
    //创建UICollectionView
    //预先默认一个UICollectionView的大小。后面为了显示完整，会对这个大小进行改动
    UICollectionView *collectionView = [[UICollectionView alloc]
            initWithFrame:CGRectMake(0, 0, 0, 300) collectionViewLayout:layout];
    collectionView.scrollEnabled = NO;  //不可滚动
    collectionView.backgroundColor = self.tableView.backgroundColor;
    collectionView.userInteractionEnabled = YES;
    self.collectionView = collectionView;
    
    //UITableView的底部视图设置为collectionView
    self.tableView.tableFooterView = collectionView;
    
    //为UICollectionView设置代理
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"WJSquareCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
}

#pragma mark -UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    UIViewController *personalCenterViewController = [[WJPersonalCenterViewController alloc] init];
//    // 必须要在跳转之前设置
//    personalCenterViewController.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:personalCenterViewController animated:YES];
    
    UIViewController *photoViewController = [[WJPhotoViewController alloc] init];
    // 必须要在跳转之前设置
    photoViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:photoViewController animated:YES];
    
}

#pragma mark -UICollectionViewDataSource
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.squareItems.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //从缓存池中获取
    WJSquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.item = self.squareItems[indexPath.row];
    
    return cell;
}

#pragma mark -UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    WJSquareItem *item = self.squareItems[indexPath.row];
    //若不是以http开头，说明不是一个网址
    if (![item.url containsString:@"http"]) {
        return;
    }
    //创建控制器并跳转
    WJWebViewController *webviewController = [[WJWebViewController alloc] init];
    webviewController.url = [NSURL URLWithString:item.url];
    // 必须要在跳转之前设置
    webviewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webviewController animated:YES];
}




@end
